package io.wdb.wxapp.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.wdb.common.exception.RspCodeEnum;
import io.wdb.common.utils.R;
import io.wdb.handler.ApiServiceHandler;
import io.wdb.modules.activity.wxapp.entity.HdUserEntity;
import io.wdb.modules.activity.wxapp.service.HdUserService;
import io.wdb.wxapp.util.CommonUtil;
import net.sf.json.JSONObject;

@RestController
@RequestMapping("wxapp")
public class WxAppUserController extends BaseController{
	private static Logger logger = LoggerFactory.getLogger(WxAppUserController.class);
	
	@Autowired
	private HdUserService hdUserService;
	
	@Autowired
	ApiServiceHandler apiServiceHandler;
//	@ApiOperation(value="微信用户信息保存", notes="微信用户信息保存")
//	@ApiImplicitParams({
//		@ApiImplicitParam(name = "appid",value = "appid", dataType = "String", paramType = "query",required=true),
//		@ApiImplicitParam(name = "openid",value = "openid", dataType = "String", paramType = "query",required=true),
//		@ApiImplicitParam(name = "mobile",value = "mobile", dataType = "String", paramType = "query",required=true),
//		@ApiImplicitParam(name = "avatar",value = "avatar", dataType = "String", paramType = "query",required=true),
//		@ApiImplicitParam(name = "nickname",value = "nickname", dataType = "String", paramType = "query",required=true),
//		@ApiImplicitParam(name = "unionid",value = "unionid", dataType = "String", paramType = "query",required=true)
//		
//	})
	public R saveWxUser(HttpServletRequest request) {
		
		checkIsNull(request.getParameter("appid"), "appid");
		checkIsNull(request.getParameter("openid"), "openid");
//		checkIsNull(request.getParameter("mobile"), "mobile");
//		checkIsNull(request.getParameter("avatar"), "avatar");
//		checkIsNull(request.getParameter("nickname"), "nickname");

		HdUserEntity userinfo = new HdUserEntity();
		if(!isEmpty(request.getParameter("mobile"))) {
			userinfo.setMobile(request.getParameter("mobile"));
		}
		if(!isEmpty(request.getParameter("nickname"))) {
			userinfo.setNickname(request.getParameter("nickname"));
		}
		if(!isEmpty(request.getParameter("avatar"))) {
			userinfo.setAvatar(request.getParameter("avatar"));
		}
		
		userinfo.setWxAppid(request.getParameter("appid"));
		userinfo.setWxOpenid(request.getParameter("openid"));
		userinfo.setUnionid(request.getParameter("unionid"));
		String hdUserId = hdUserService.save(userinfo);
		Map<String, Object> result = new HashMap<>();
		result.put("hdUserId", hdUserId);
		
		return R.ok(result);
	}
	
	@RequestMapping(value = "activityShareInfo", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value="返回hdUserId", notes="返回hdUserId分享时会用到")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "usertoken",value = "api接口返回的usertoken,测试用header中有", dataType = "String", paramType = "query",required=true),
		@ApiImplicitParam(name = "userid",value = "api接口返回的userid，如果有必传", dataType = "String", paramType = "query",required=false),
		@ApiImplicitParam(name = "appId",value = "appId，测试用header中有", dataType = "String", paramType = "query",required=false),
		@ApiImplicitParam(name = "mobile",value = "api接口返回的mobile，如果有必传", dataType = "String", paramType = "query",required=false)
		
	})
	public R saveWxUserByToken(HttpServletRequest request) {
		String appid = request.getHeader("appId");//放置在Header中
		if(isEmpty(appid)) appid = request.getParameter("appId");
		String userid = request.getParameter("userid");
		String usertoken =  request.getHeader("token");
		if(isEmpty(usertoken)) usertoken = request.getParameter("usertoken");
		String mobile = request.getParameter("mobile");
		logger.info("activityShareInfo 请求：appid {}，usertoken {}，userid {},mobile {}", appid, usertoken, userid, mobile);
		checkIsNull(appid,"appid");
		checkIsNull(usertoken,"usertoken");

		HdUserEntity userinfo = hdUserService.getUserinfoByUsertoken(null, appid, userid, usertoken, mobile);
		//根据userid/usertoken请求获取userinfo信息，包含mobile,nickname,avatar，openid，unionid等字段
		if(isEmpty(userinfo) || isEmpty(userinfo.getSessionKey())) {//如果返回为空，表示usertoken过期
			return R.error(RspCodeEnum.USER_TOKEN_IS_UNVALID.getRspCode(), RspCodeEnum.USER_TOKEN_IS_UNVALID.getRspMsg());
		}
		Map<String, Object> result = new HashMap<>();
		result.put("hdUserId", userinfo.getId());
		return R.ok(result);
	}
	
	
	@RequestMapping(value="/getReadingList", method=RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="查询用户阅读记录", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "userid",value = "当前用户id", dataType = "String",  required=true),
		@ApiImplicitParam(name = "encryptedData",value = "加密数据", dataType = "String", required=true),
		@ApiImplicitParam(name = "iv", value = "加密算法的初始向量", dataType = "String", required=true),
		@ApiImplicitParam(name = "sessionKey", value = "sessionKey", dataType = "String", required=true),
		@ApiImplicitParam(name = "activity_id", value = "活动ID", dataType = "String", required=true)
	})
	public R getReadingList(HttpServletRequest request){
		Map<String, Object> result = new HashMap<>();
		String encryptedData = request.getParameter("encryptedData");
		String iv = request.getParameter("iv");
		String sessionKey = request.getParameter("sessionKey");
		String groupId = "";
		try {
			groupId = CommonUtil.decrypt(encryptedData, iv, sessionKey);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error(10001, "decrypt error,"+ groupId);
		}
		String activity_id = request.getParameter("activity_id");
		String userId = request.getParameter("userid");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("groupId", groupId);
		params.put("activityId", activity_id);
		params.put("userId", userId);
		logger.info("查询用户阅读记录getReadingList's request: [{}]", JSON.toJSONString(params));
		result = hdUserService.queryReadingList(params);
		logger.info("查询用户阅读记录getReadingList's response: [{}]", JSON.toJSONString(result));
		return R.ok(result);
	}
}
